import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import VueDevTools from 'vite-plugin-vue-devtools'


console.log("环境", process.env.NODE_ENV === "production" ? '/ai_closet' : '/',);


// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production'
  return {
    base: isProduction ? '/ai_closet' : '/',
    plugins: [
      vue(),
      vueJsx(),
      VueDevTools(),
    ],
    build: {
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: false,
          drop_debugger: true,
        },
      },
      chunkSizeWarningLimit: 4096,
      rollupOptions: {
        output: {
          assetFileNames(assetsInfo) {
            const patterns: [RegExp, string][] = [
              [/\.css$/, 'css/[name]-[hash][extname]'],
              [/\.(png|jpe?g|gif|bmp|svg)$/, 'img/[name]-[hash][extname]'],
              [/\.(ttf|woff2?|eot|otf)$/, 'font/[name]-[hash][extname]']
            ]
            const matchedPattern = patterns.find(([regex]) =>
              regex.test(assetsInfo.name!)
            )?.[1]
            return matchedPattern || '[name]-[hash][extname]'
          },
          entryFileNames(chunkInfo) {
            return 'js/[name]-[hash].js'
          },
          // 保持components目录结构
          chunkFileNames: (chunkInfo) => {
            const pathPatterns: [string, string][] = [
              ['/components/', 'js/components/[name]-[hash].js'],
              ['/views/', 'js/views/[name]-[hash].js'],
              ['/stores/', 'js/stores/[name]-[hash].js'],
              ['/config/', 'js/config/[name]-[hash].js'],
              ['/directives/', 'js/directives/[name]-[hash].js'], // 统一小写
              ['/utils/', 'js/utils/[name]-[hash].js']
            ]

            // 统一处理路径分隔符（兼容Windows）
            const normalizedIds = chunkInfo.moduleIds.map(id =>
              id.replace(/\\/g, '/').toLowerCase()
            )

            // 使用find进行模式匹配
            const matchedPattern = pathPatterns.find(([pathSegment]) =>
              normalizedIds.some(id => id.includes(pathSegment))
            )

            return matchedPattern?.[1] || 'js/[name]-[hash].js'
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0',
      port: 8888,
      hmr: true
      // open: true,
      // proxy: {
      //   '/api': {
      //     target: 'http://localhost:3000',
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, '')
      //   }
      // }
    }
  }
})
